package com.ai.cltcore.control;

import java.lang.reflect.Method;
import java.util.Map;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.ai.common.xml.util.ControlConstants;
import com.ai.frame.IControlService;
import com.ai.frame.bean.InputObject;
import com.ai.frame.bean.OutputObject;
import com.cmos.core.logger.LoggerFactory;
import com.cmos.core.logger.Logger;
import com.ai.frame.util.JsonUtil;
import com.ai.cltcore.util.StringUtil;
import com.ai.cltcore.util.Constants.MQ_TOPIC;
import com.ai.cltcore.util.DedicException;

/**
 */
public class ControlServiceImpl implements IControlService, BeanFactoryAware {
	private static final Logger LOGGER = LoggerFactory
			.getApplicationLog(ControlServiceImpl.class);

	private BeanFactory factory;

	public void setBeanFactory(BeanFactory factory) {
		this.factory = factory;
	}

	@SuppressWarnings("deprecation")
	public String execute(String json) {
		InputObject inObj = null;
		OutputObject outObj = new OutputObject();
		long start = System.currentTimeMillis();
		try {
			inObj = JsonUtil.json2InputObject(json);
			outObj.setReturnCode(ControlConstants.RETURN_CODE.IS_OK);
			if (inObj != null) {
				LOGGER.info("INVOKE START!", "service=" + inObj.getService() + ", method=" + inObj.getMethod() + ", dataSource=" + inObj.getParams().get("dataSource")
						+", inputObject = " +JsonUtil.convertObject2Json(inObj));
				// 分库逻辑指定数据源 By Chengfang.Su 2017.08.07 暂不配置默认数据源(无值或错误标示,异常返回)
				Object object = factory.getBean(inObj.getService());
				Method mth = object.getClass().getMethod(inObj.getMethod(), InputObject.class, OutputObject.class);
				mth.invoke(object, inObj ,outObj);
				
				LOGGER.info("INVOKE SECCESS!", "COST="+(System.currentTimeMillis() - start)+"ms"+", outputObject = "+JsonUtil.convertObject2Json(outObj));
			} else {
				throw new DedicException("InputObject can't be null !!!");
			}
		} catch (Exception e) {
			if (inObj != null && inObj.getLogParams() != null && StringUtil.isNotEmpty(inObj.getLogParams().get("OP_REQST_NO"))) {
				LOGGER.error("execute INVOKE ERROR! ", "OP_REQST_NO = " + inObj.getLogParams().get("OP_REQST_NO") + ",  JSON = "+ json , e);
			} else {
				LOGGER.error("execute INVOKE ERROR! ", "JSON = "+ json, e);
			}
			// 异常处理
			outObj.setReturnCode(ControlConstants.RETURN_CODE.SYSTEM_ERROR);
			outObj.setReturnMessage(e.getMessage() == null ? e.getCause().getMessage() : e.getMessage());
		}
		return JsonUtil.outputObject2Json(outObj);
	}
	
	/**
	 * 记录操作日志
	 * 
	 * @param startTime
	 *            开始时间
	 * @param endTime
	 *            结束时间
	 * @param inputObject
	 *            入参
	 *            </br>logParam中存放公用信息，如用户信息
	 *            </br>params存放参数信息
	 * @param outputObject
	 *            出参
	 */
	@SuppressWarnings("deprecation")
	public void saveUserOperLog(long startTime, long endTime, InputObject inObj, OutputObject outObj) {
		if("saveOperLog".equals(inObj.getMethod()) || StringUtil.isEmpty("LOGIN_LG_ID")){
			return;
		}
		try {
			long duringMs = endTime - startTime;
			Map<String, String> logMap = inObj.getLogParams();
			logMap.put("OP_TYPE_CD", "1");
			logMap.put("duringMs", String.valueOf(duringMs));
			logMap.put("INVK_SRV_NM", inObj.getService());
			logMap.put("INVK_MTHD_NM", inObj.getMethod());
			logMap.put("OP_RSLT_CD", outObj.getReturnCode());
			logMap.put("BACKTO_RSLT_CNTT", outObj.getReturnMessage());
			String param = JsonUtil.convertObject2Json(inObj.getParams());
			if (StringUtil.isNotEmpty(param) ) {
				logMap.put("REQST_PARA_CNTT", param);
			}
			
			logMap.put("OP_SRC_CD", "2");
			InputObject inputObject = new InputObject("userService", "saveOperLog", logMap);
			Object object = factory.getBean("queueService");
			Method mth = object.getClass().getMethod("sendMsg2MQ", String.class,String.class, InputObject.class);
			LOGGER.info("saveUserOperLog", mth.invoke(object, MQ_TOPIC.TOPIC_OPER_LOG ,logMap.get("LOGIN_LG_ID"), inputObject)+"");
			
		} catch (Exception e) {
			LOGGER.error("saveUserOperLog", "批量记录操作日志失败!", e);
		}
	}
}
